package com.shine.minepressure.ui.history;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.OnCancelListener;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lxj.xpopup.interfaces.SimpleCallback;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.shine.minepressure.BR;
import com.shine.minepressure.R;
import com.shine.minepressure.app.Constants;
import com.shine.minepressure.base.BaseFragment;
import com.shine.minepressure.bean.AreaMessageBean;
import com.shine.minepressure.bean.AreaSensorMessageBean;
import com.shine.minepressure.bean.IportHisFaultBean;
import com.shine.minepressure.bean.StationMessageBean;
import com.shine.minepressure.databinding.FragmentHistoryChild3Binding;
import com.shine.minepressure.http.ApiException;
import com.shine.minepressure.http.ECObserver;
import com.shine.minepressure.http.RetrofitClient;
import com.shine.minepressure.http.RxUtils;
import com.shine.minepressure.http.Service;
import com.shine.minepressure.ui.adapter.HistoryDataFragment3Adapter;
import com.shine.minepressure.ui.history.viewModel.HistoryDataChildViewModel;
import com.shine.minepressure.utils.DateUtils;
import com.shine.minepressure.view.pop.History3DataPopup;

import java.util.ArrayList;
import java.util.List;

public class HistoryDataChild3Fragment extends BaseFragment<FragmentHistoryChild3Binding, HistoryDataChildViewModel> {
    private HistoryDataFragment3Adapter historyDataFragment3Adapter;
    private History3DataPopup history3DataPopup;
    private int page = 1;
    private int mAreaPosition, mAreaSensorPosition, mStationPosition;
    private String mAreaName, mSensorName, mStationName;

    private static List<AreaMessageBean.RowsDTO> mAreaMessageList = new ArrayList<>();
    private static List<String> mAreaMessage = new ArrayList<>();

    private List<AreaSensorMessageBean.RowsDTO> areaSensorMessageList = new ArrayList<>();
    private List<String> mAreaSensorMessage = new ArrayList<>();

    private static List<StationMessageBean.RowsDTO> mStationMessageList = new ArrayList<>();
    private static List<String> mStationMessage = new ArrayList<>();

    private String mAreaId;
    private String mStationId = "-1";
    private String mIportId = "-1";
    private String mBeginTime = DateUtils.getCurrDate(DateUtils.LONG_DATE + " 00:00:00");
    private String mEndTime = DateUtils.getCurrDate(DateUtils.LONG_DATE + " 23:59:59");

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_history_child3;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public HistoryDataChildViewModel initViewModel() {
        return new HistoryDataChildViewModel(getActivity());
    }

    @Override
    public void initData() {
        super.initData();

        historyDataFragment3Adapter = new HistoryDataFragment3Adapter(binding.recyclerView);
        binding.recyclerView.setAdapter(historyDataFragment3Adapter);

        binding.refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                binding.refreshLayout.finishRefresh(1000);
                binding.refreshLayout.setEnableLoadMore(true);
                historyDataFragment3Adapter.clear();
                page = 1;
                getIportHisFault();
            }
        });
//        binding.refreshLayout.setEnableLoadMore(false);
        binding.refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                binding.refreshLayout.finishLoadMore(1000);
                page++;
                getIportHisFault();
            }
        });

        binding.search.setOnClickListener(this);

        getAreaMessage();
        getIportHisFault();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.search:
                search();
                break;
        }
    }

    public static void setStationMessage(List<StationMessageBean.RowsDTO> areaStationList, List<String> stationMessage) {
        mStationMessageList.clear();
        mStationMessage.clear();
        mStationMessageList.addAll(areaStationList);
        mStationMessage.add("全部");
        mStationMessage.addAll(stationMessage);
    }

    /**
     * 测区列表
     */
    private void getAreaMessage() {
//        showLoading("");
        RetrofitClient.getInstance().create(Service.class)
                .getAreaMessage()
                .compose(RxUtils.bindToLifecycle(this))
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .subscribe(new ECObserver<AreaMessageBean>() {
                    @Override
                    protected void _onNext(AreaMessageBean areaMessageBean) {
//                        dismissLoading();

                        if (areaMessageBean.getTotal().equals("0"))
                            return;
                        for (AreaMessageBean.RowsDTO rowsDTO : areaMessageBean.getRows()) {
                            mAreaMessage.add(rowsDTO.getArea_Name());
                        }
                        mAreaMessageList.addAll(areaMessageBean.getRows());
                    }

                    @Override
                    protected void _onError(ApiException ex) {
                        ToastMessage(ex.message);
                        dismissLoading();
                    }
                });
    }

    /**
     * 获取指定测区传感器
     */
    private void getAreaSensorMessage() {
        showLoading("");
        RetrofitClient.getInstance().create(Service.class)
                .getAreaSensorMessage(mAreaId, "")
                .compose(RxUtils.bindToLifecycle(this))
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .subscribe(new ECObserver<AreaSensorMessageBean>() {
                    @Override
                    protected void _onNext(AreaSensorMessageBean areaSensorMessageBean) {
                        dismissLoading();

                        if (areaSensorMessageBean.getTotal().equals("0"))
                            return;
                        areaSensorMessageList.clear();
                        mAreaSensorMessage.clear();
                        mAreaSensorMessage.add("全部");
                        areaSensorMessageList.addAll(areaSensorMessageBean.getRows());
                        for (AreaSensorMessageBean.RowsDTO rowsDTO : areaSensorMessageList) {
                            mAreaSensorMessage.add(rowsDTO.getSensorTypeName());
                        }
                        history3DataPopup.setAreaSensorMessage(mAreaSensorMessage);
                    }

                    @Override
                    protected void _onError(ApiException ex) {
                        ToastMessage(ex.message);
                        dismissLoading();
                    }
                });
    }

    /**
     * 历史端口故障
     */
    private void getIportHisFault() {
        showLoading("");
        RetrofitClient.getInstance().create(Service.class)
                .getIportHisFault(mStationId, mIportId, mBeginTime, mEndTime, Constants.PAGE_SIZE + "", page + "")
                .compose(RxUtils.bindToLifecycle(this))
                .compose(RxUtils.schedulersTransformer())
                .compose(RxUtils.exceptionTransformer())
                .subscribe(new ECObserver<IportHisFaultBean>() {
                    @Override
                    protected void _onNext(IportHisFaultBean iportHisFaultBean) {
                        dismissLoading();

                        binding.totalNum.setText(iportHisFaultBean.getTotal() + "");
                        historyDataFragment3Adapter.addMoreData(iportHisFaultBean.getRows());
                        if (iportHisFaultBean.getRows().size() < Constants.PAGE_SIZE) {
                            binding.refreshLayout.setEnableLoadMore(false);
                        }
                    }

                    @Override
                    protected void _onError(ApiException ex) {
                        ToastMessage(ex.message);
                        dismissLoading();
                    }
                });
    }

    private void search() {
        history3DataPopup = new History3DataPopup(getActivity(), mAreaMessage, mAreaSensorMessage, mStationMessage, mAreaName, mSensorName, mStationName,
                mBeginTime, mEndTime,
                mAreaPosition, mAreaSensorPosition, mStationPosition);
        new XPopup.Builder(getActivity())
                .moveUpToKeyboard(false) //如果不加这个，评论弹窗会移动到软键盘上面
                .enableDrag(true)
                .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
//                        .isThreeDrag(true) //是否开启三阶拖拽，如果设置enableDrag(false)则无效
                .setPopupCallback(new SimpleCallback() {
                    @Override
                    public void onShow(BasePopupView popupView) {
                    }

                    @Override
                    public void onDismiss(BasePopupView popupView) {
                    }
                })
                .asCustom(history3DataPopup)/*.enableDrag(false)*/
                .show();
        history3DataPopup.show();
        history3DataPopup.setListener(new OnConfirmListener() {
            @Override
            public void onConfirm() {
            }
        }, new OnCancelListener() {
            @Override
            public void onCancel() {
            }
        }, new History3DataPopup.OnPopClickListener() {

            @Override
            public void getSensorMessage(Integer mAreaPosition) {
                if (mAreaMessageList.size() == 0) {
                    ToastMessage("请先选择测区列表");
                } else {
                    mAreaId = mAreaMessageList.get(mAreaPosition).getArea_Id();
                    getAreaSensorMessage();
                }
            }

            @Override
            public void onConfirmClick(String areaName, String sensorName, String stationName,
                                       String beginTime, String endTime,
                                       int areaPosition, int areaSensorPosition, int stationPosition
            ) {
                mAreaName = areaName;
                mSensorName = sensorName;
                mStationName = stationName;

                mBeginTime = beginTime;
                mEndTime = endTime;

                mAreaPosition = areaPosition;
                mAreaSensorPosition = areaSensorPosition;
                mStationPosition = stationPosition;

                if (stationPosition == 0)
                    mStationId = "-1";
                else
                    mStationId = mStationMessageList.get(stationPosition - 1).getStationID();

                if (areaSensorPosition == 0)
                    mIportId = "-1";
                else
                    mIportId = areaSensorMessageList.get(areaSensorPosition - 1).getIportID();

                binding.refreshLayout.setEnableLoadMore(true);
                historyDataFragment3Adapter.clear();
                page = 1;
                getIportHisFault();
            }
        });
    }

}